﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;

namespace BK_SERVER
{
    public partial class BK_SERVER : Form
    {
        private delegate void UpdateStatusCallback(string strMessage);
        ServerProcess server;
        public BK_SERVER()
        {
            InitializeComponent();
        }
        ~BK_SERVER()
        {
            ServerProcess.ExitServer();
            ProcessClient.Exit();
            server.killThread();
            this.Dispose();
            this.Close();
        }
        private void buttonActive_Click(object sender, EventArgs e)
        {
            int check = 0;
            try
            {
                IPAddress ipServer = IPAddress.Parse(textBoxIP.Text);
                string portServer = textBoxPort.Text.ToString();
                buttonActive.Enabled = false;
                ServerProcess.StatusChanged += new StatusChangedEventHandler(mainServer_StatusChanged);
                server = new ServerProcess(ipServer, portServer);
                server.StartListenning();
            }
            catch
            {
                check = 1;
                MessageBox.Show("Không thể khởi động Server\nVui lòng thử lại sau");
                buttonActive.Enabled = true;
                exitToolStripMenuItem_Click(sender, e);
                return;
            }
            if(check == 0)
                MessageBox.Show("Server đang khởi chạy... lắng nghe tại:\nIP server: 192.168.7.124\nPort server: 90");
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                ServerProcess.ExitServer();
                ProcessClient.Exit();
                if(server != null)
                    server.killThread();                
                this.Close();
            }
            catch { }
        }
        
        public void mainServer_StatusChanged(object sender, StatusChangedEventArgs e)
        {
            // Call the method that updates the form
            this.Invoke(new UpdateStatusCallback(this.UpdateStatus), new object[] { e.EventMessage });
        }
        private void UpdateStatus(string strMessage)
        {
            // Updates the log with the message
            listBoxClient.Items.Add(strMessage);
        }

        private void helpToolStripMenuItem_Click(object sender, EventArgs e)
        {
            const string msg = "BTL Công nghệ .Net";
            const string caption = "BK Messenger's Information";
            MessageBox.Show(null, msg, caption, MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }
}
